package upload.demo.vue_springboot_upload.handler;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

//事件处理
@Component
//@Slf4j
public class SocketIOHandler {
	private static final Logger log = LoggerFactory.getLogger(SocketIOHandler.class);

	@Autowired
	private SocketIOServer server;// 当前服务端对象

	// 初始化时触发这个方法
	// 服务器启动
	@PostConstruct
	private void autoStartup() {
		server.addListeners(this);
		server.start();
		System.out.println("服务器启动成功");
	}

	// 当一个bean从spring容器中被销毁前触发这个方法
	// 服务端关闭
	// @PreDestroy注解用于在Bean被销毁之前执行清理操作
	@PreDestroy
	private void autoStop() {

		if (server == null) {
			log.info("autoStop .... server is null !");
		} else {
			log.info("autoStop .... server is not null !");

			server.stop();
			System.out.println("服务器断开连接");
		}

	}

	// 客户端连接的时候触发
	// 监听客户端的connect事件
	// SocketIOClient代表一个客户端连接（客户端的对象），它提供了发送和接收消息的方法。通过此SocketIOClient对象，服务器可以针对该客户端发送消息
	@OnConnect
	public void onConnect(SocketIOClient client) {

		log.info("onConnect 已连接客户端:" + client.getSessionId() + " " + client.getHandshakeData().getUrl());
	}

	// 客户端关闭连接时触发
	// 监听客户端的disconnect事件
	@OnDisconnect
	public void onDisconnect(SocketIOClient client) {

	}

	@OnEvent("fileUpload")
	public void onEventFileUpload(Object data, SocketIOClient client) throws JSONException {

		// server.getBroadcastOperations().sendEvent("fileUploaded", responseData);
	}

	@OnEvent("fileDownload")
	public void onFileDownload(SocketIOClient client, JSONObject data, AckRequest ackRequest) throws JSONException {

	}
}
